# Filename: Skytank_mutex.py
# Author: Torrey Umland
# Description: this file holds class definition and functions for a locking mechanism
import time

SKYTANKMUTEX_LOCKTIMEOUT = 30

class SkytankMutex:
    locktime=0
    openL=1
    callLock=0
    lockholder=''
    #acquires the lock, returns 1 for success, returns 0 for failure
    def acquire_lock(self,callLock=0,lockholder=''):
        lockresult=0
        #if lock is available (openL == 1), claim it
        if self.openL:
            self.openL=0
            self.locktime = time.time()
            self.callLock = callLock
            self.lockholder = lockholder
	    #report success
            print "Successfully acquired lock!"
            lockresult=1
        #otherwise check for time out if its a chat lock, not a call lock
        elif self.openL==0 and self.callLock==0:
            if int(time.time()) - int(self.locktime) >= SKYTANKMUTEX_LOCKTIMEOUT:
                #lock has timed out,give to new requestor
                self.openL=0
                self.callLock=callLock
                self.locktime=time.time()
                #pass lock off to new holder
                self.lockholder = lockholder
                #report success
                print "Successfully acquired lock! (Previous user timed out)"
                lockresult=1
                #if it is a call lock
        elif self.callLock:
            print "Could not acquire locked lock! (call lock)"
        else:
            print "Could not acquire locked lock! (chat lock)"
        return lockresult
		
    def release_lock(self):
        if self.openL==0:
            self.openL=1
            self.lockholder=''
            locktime=0
            callLock=0

    def has_lock(self,username=''):
        #returns True if user has the lock
        return self.lockholder==username

    def who_has_lock(self):
        return self.lockholder
    
